Below is a function that ought to return “I’m an even number!” if
x is an even number. However, we’re having trouble
receiving a value despite x == 4, which we know is an even
number. Fix the code chunk and explain why this error is occurring. You
will have to change the eval=FALSE option in the code chunk
header to get the chunk to knit in your PDF.
NOTE: %% is the “modulo” operator, which returns the
remainder when you divide the left number by the right number. For
example, try 2 %% 2 (should equal 0 as 2/2 = 1 with no
remainder) and 5 %% 2 (should equal 1 as 5/2 = 2 with a
remainder of 1).
return_even <- function(x){
if (x %% 2 == 0) {
return("I'm an even number!")
}
}
x <- 4
return_even(x)
EXPLAIN THE ISSUE HERE: the return_even function call was missing the input argument x.
R functions are not able to access global variables unless we provide them as inputs.
Below is a function that determines if a number is odd and adds 1 to that number. The function ought to return that value, but we can’t seem to access the value. Debug the code and explain why this error is occurring. Does it make sense to try and call odd_add_1 after running the function?
return_odd <- function(y){
if (y %% 2 != 0) {return(y + 1)}}
return_odd(2)
EXPLAIN THE ISSUE HERE: - the function was missing a return statemnt. - ommited the odd_add_1 variable from the function definition and from the function call. it doesn’t make sense to call odd_add_1 because odd_add_1 doesn’t exist and thus we can’t call it.
BMI calculations and conversions: - metric: - imperial: - 1 foot = 12 inches - 1 cm = 0.01 meter
Below is a function bmi_imperial() that calculates BMI
and assumes the weight and height inputs are from the imperial system
(height in feet and weight in pounds).
df_colorado <- read_csv("data/colorado_data.csv")
## Rows: 24 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): location, gender
## dbl (3): height, weight, date
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
bmi_imperial <- function(height, weight){
bmi = (703 * weight)/(height * 12)^2
return(bmi)
}
# calculate bmi for the first observation
bmi_imperial(df_colorado$height[1], df_colorado$weight[1])
## [1] 42.62802
Write a function called bmi_metric() that calculates BMI
based on the metric system. You can test your function with the Taiwan
data set excel file in the data folder, which has height in cm and
weight in kg.
library(readxl)
df_taiwan <- read_excel("~/PHW251_Fall2022/problem sets/problem set bonus/data/taiwan_data.xlsx")
bmi_metric <- function(height, weight){
bmi = (weight)/(height/100)^2
return(bmi)}
# uncomment the line below to test the bmi calculation on the first row
bmi_metric(df_taiwan$height[1], df_taiwan$weight[1])
## [1] 21.45357
Can you write a function called calculate_bmi() that
combines both of the BMI functions? You will need to figure out a way to
determine which calculation to perform based on the values in the
data.
calculate_bmi <- function( height, weight ) {
tallest_person_ft = 8 + 11.1/12 # 8 ft 11.1 inches tall
bmi <- if_else( height >= as.vector(tallest_person_ft),
bmi_metric(height,weight ),
bmi_imperial( height,weight )
)
return(bmi)}
# test
calculate_bmi(df_colorado$height[1], df_colorado$weight[1])
## [1] 42.62802
calculate_bmi(df_taiwan$height[1], df_taiwan$weight[1])
## [1] 21.45357
Use your function calculate_bmi() to answer the
following questions:
What is the average BMI of the individuals in the Colorado data set?
mean(calculate_bmi(df_colorado$height, df_colorado$weight))
## [1] 45.60881
What is the average BMI of the individuals in the Taiwan data set?
mean(calculate_bmi(df_taiwan$height, df_taiwan$weight))
## [1] 22.99287
Combine the Colorado and Taiwan data sets into one data frame and
calculate the BMI for every row using your calculate_bmi()
function. Print the first six rows and the last six rows of that new
data set.
df_merged <- rbind(df_colorado, df_taiwan)
all_bmi <- calculate_bmi(df_merged$height, df_merged$weight)
head(all_bmi, 6)
## [1] 42.62802 31.60461 65.91335 70.06356 51.68774 62.09903
tail(all_bmi, 6)
## [1] 24.85795 24.41928 27.80329 20.51509 22.94812 21.93635
Make a boxplot that shows the BMI distribution of the combined data, separated by location on the x-axis. Use a theme of your choice, put a title on your graph, and hide the y-axis title.
NOTE: These data are for practice only and are not representative populations, which is why we aren’t comparing them with statistical tests. It would not be responsible to draw any conclusions from this graph!
boxplot(all_bmi ~ df_merged$location,
main="Boxplot of BMI by location",
xlab="Location",
ylab="")
Recall the patient data from a healthcare facility that we used in Part 2 of Problem Set 7.
We had four tables that were relational to each other and the following keys linking the tables together:
Use a join to find out which patients have no visits on the schedule.
anti_join_table <- anti_join(patients, schedule, by=c("patient_id"))
anti_join_table
patient_id <dbl> | age <dbl> | race_ethnicity <chr> | gender_identity <chr> | height <dbl> | weight <dbl> |
|---|---|---|---|---|---|
| 1013 | 32 | NA | man | 180.00 | 58.00 |
| 1015 | 71 | White | man | 151.00 | 62.00 |
| 1017 | 72 | Asian | woman | 191.00 | 62.00 |
| 1023 | 48 | Asian | man | 4.82 | 202.86 |
| 1033 | 64 | Asian | woman | 6.43 | 255.78 |
| 1038 | 38 | African American/Black | transgender | 4.86 | 341.78 |
| 1042 | 66 | White | man | 4.95 | 251.37 |
With this data, can you tell if those patients with no visits on the schedule have been assigned to a doctor? Why or why not?
# your code here? (optional)
No, we cannot because these patients have no associated visit_id (in the schedule dataset) and therefore we cannot link them to any doctors (in the visits dataset).
Assume those patients need primary care and haven’t been assigned a doctor yet. Which primary care doctors have the least amount of visits? Rank them from least to most visits.
full_join(visits, doctors, by="doctor_id") %>%
group_by(doctor_id, doctor) %>%
summarise(num_visits = n()) %>%
arrange(num_visits)
## `summarise()` has grouped output by 'doctor_id'. You can override using the
## `.groups` argument.
doctor_id <dbl> | doctor <chr> | num_visits <int> | ||
|---|---|---|---|---|
| 5009 | Giuseppe Serrano | 1 | ||
| 5015 | Aron Randolph | 1 | ||
| 5021 | Jemima Velazquez | 2 | ||
| 5000 | Daanyaal Griffin | 3 | ||
| 5005 | Jamie-Lee Wilder | 3 | ||
| 5006 | Merlin Jacobs | 3 | ||
| 5010 | Irfan Mcghee | 3 | ||
| 5011 | Ishaaq Matthews | 3 | ||
| 5013 | Abdul Bostock | 3 | ||
| 5016 | Maleeha Cowan | 3 |
Doctors Giuseppe Serrano and Aron Randolph have the least amount of visits (1 visit each)
Recall in Problem Set 5, Part 2, we were working with data from [New York City] (https://data.cityofnewyork.us/Health/Children-Under-6-yrs-with-Elevated-Blood-Lead-Leve/tnry-kwh5) that tested children under 6 years old for elevated blood lead levels (BLL). [You can read more about the data on their website]).
About the data:
All NYC children are required to be tested for lead poisoning at around age 1 and age 2, and to be screened for risk of lead poisoning, and tested if at risk, up until age 6. These data are an indicator of children younger that 6 years of age tested in NYC in a given year with blood lead levels (BLL) of 5 mcg/dL or greater. In 2012, CDC established that a blood lead level of 5 mcg/dL is the reference level for exposure to lead in children. This level is used to identify children who have blood lead levels higher than most children’s levels. The reference level is determined by measuring the NHANES blood lead distribution in US children ages 1 to 5 years, and is reviewed every 4 years.
Load in a cleaned-up version of the blood lead levels data:
bll_nyc_per_1000 <- read_csv("data/bll_nyc_per_1000.csv")
## Rows: 20 Columns: 3
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): borough_id
## dbl (2): time_period, bll_5plus_1k
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Create a formattable table (example below) that shows the elevated blood lead levels per 1000 tested across 2013-2016. If the BLL increases from the previous year, turn the text red. If the BLL decreases from the previous year, turn the text green. To accomplish this color changing, you may want to create three indicator variables that check the value between years (e.g. use if_else). If you’ve have used conditional formatting on excel/google sheets, the concept is the same, but with R.
Note: If you are using if_else (hint hint) and checking by the year, you will likely need to use the left quote, actute, backtip, to reference the variable.
We have also provided you a function that you can use within your formattable table to reference this indicator variable to help reduce the code. However, you do not have to use this, and feel free to change the hex colors.
# in the event that plotly was run below, detach plotly
# the option 'style' conflicts when both libraries are loaded
#detach("package:plotly", unload=TRUE)
# function that returns red if indicator == 1, green otherwise
up_down = function(indicator) {
return(ifelse( indicator == TRUE, "#fd626e", "#03d584"))
}
pivot_table <- bll_nyc_per_1000 %>% pivot_wider(
names_from= time_period,
values_from = bll_5plus_1k)
increased2014 <- if_else(pivot_table$`2014` > pivot_table$`2013` , TRUE, FALSE)
increased2015 <- if_else(pivot_table$`2015` > pivot_table$`2014` , TRUE, FALSE)
increased2016 <- if_else(pivot_table$`2016` > pivot_table$`2015` , TRUE, FALSE)
pivot_table
borough_id <chr> | 2013 <dbl> | 2014 <dbl> | 2015 <dbl> | 2016 <dbl> |
|---|---|---|---|---|
| Bronx | 20.1 | 18.7 | 15.7 | 15.0 |
| Brooklyn | 30.2 | 26.8 | 22.6 | 22.3 |
| Manhattan | 15.2 | 14.1 | 10.6 | 8.1 |
| Queens | 18.2 | 18.5 | 15.4 | 14.3 |
| Staten Island | 17.6 | 17.1 | 12.0 | 14.8 |
# your `formattable code` here
formattable(pivot_table, col.names= c("Borough", "2013", "2014", "2015","2016"),
align=c("l",rep("r",NCOL(pivot_table)-1)),
list(
`borough_id`=formatter("span",style= ~style(color="grey",
font.weight="bold")),
`2014` = formatter("span",
style= ~ style(color=up_down(increased2014))),
`2015` = formatter("span",
style= ~ style(color=up_down(increased2015))),
`2016` = formatter("span",
style= ~ style(color=up_down(increased2016)))
))
| Borough | 2013 | 2014 | 2015 | 2016 |
|---|---|---|---|---|
| Bronx | 20.1 | 18.7 | 15.7 | 15.0 |
| Brooklyn | 30.2 | 26.8 | 22.6 | 22.3 |
| Manhattan | 15.2 | 14.1 | 10.6 | 8.1 |
| Queens | 18.2 | 18.5 | 15.4 | 14.3 |
| Staten Island | 17.6 | 17.1 | 12.0 | 14.8 |
Starting with the data frame bll_nyc_per_1000 create a
table with the DT library showing elevated blood lead levels per 1000
tested in 2013-2016 by borough. Below is an example of the table to
replicate.
datatable(bll_nyc_per_1000,
options = list(
pageLength=10,
search = list(regex = TRUE, caseInsensitive = FALSE, search = ''),
lengthMenu=c(5,10,15,60),
# order=list(0,"desc"),
columnDefs=list(
list(className='dt-center',targets=1:3))),
rownames=FALSE,
caption="New York City: Elevated Blook Lead Levels 2013-2016 by Borough",
colnames=c("Borough","Year","BLL>5"),
editable=list(target='cell',disable=list(columns=1:3))
) %>%
formatRound(3,1)
For this question, we will use suicide rates data that comes from [the CDC] (https://www.cdc.gov/nchs/pressroom/sosmap/suicide-mortality/suicide.htm).
Replicate the graph below using plotly.
fig_1 <- plot_ly(df_suicide_filtered,
x = ~YEAR, y = ~RATE, type = 'scatter',
linetype = ~STATE, mode="lines") %>%
layout(title=
"Suicide Rates by State Over Time",
xaxis=list(title='', dtick = "M1", tickformat="Y"),
yaxis=list(title='Case Rates per 100,000'),
legend=list(title=list(text='Region'),
orientation = 'v'))
fig_1
## Warning: `arrange_()` was deprecated in dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
## Warning: plotly.js only supports 6 different linetypes
Create an interactive (choropleth) map with plotly similar to the one presented on the CDC website. On the CDC map you can hover over each state and see the state name in bold, the death rate, and deaths. We can do much of this with plotly. As a challenge, use only the 2018 data to create an interactive US map colored by the suicide rates of that state. When you hover over the state, you should see the state name in bold, the death rate, and the number of deaths.
Some key search terms that may help:
Below is an image of an example final map when you hover over California.
Here is the
shell of the map to get you started. Copy the plotly code into the chunk
below this one and customize it.
# data pulled from CDC website described above
df_suicide <- read_csv("data/Suicide Mortality by State.csv") %>%
filter(YEAR == 2018)
plot_ly(df_suicide,
type="choropleth",
locationmode = "USA-states") %>%
layout(geo=list(scope="usa"))
df_suicide$hover <- with(df_suicide, paste(NAME, '<br>', "Dath Rate: ",
RATE, "<br>", "Deaths", DEATHS))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa')
)
fig <- plot_geo(df_suicide, locationmode = 'USA-states')
fig <- fig %>% add_trace(
zmin = 8, zmax=25,
z = ~RATE, text = ~hover, locations = ~STATE,
hoverinfo = "text",
color = ~RATE
)
fig <- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
title = 'Suicide Mortality by State in 2018<br>The number of
deaths per 100,000 population',
geo = g)
fig